<template>
  <view class="chat-container">
    <scroll-view class="chat-window" scroll-y="true" :scroll-into-view="'msg-' + lastMessageId">
      <!-- 循环显示每条消息 -->
      <view v-for="(msg, index) in messages" :key="index" :id="'msg-' + index" class="chat-message"
        :class="{ 'user-message': msg.isUser }">

        <!-- 机器人头像 -->
        <view class="message-avatar">
          <image v-if="!msg.isUser" class="avatar" src="/static/brick.png"></image>
        </view>
        <!-- 消息内容 -->
        <view class="message-bubble" :class="{ 'user-bubble': msg.isUser }">
          <MarkdownViewer :markdown="msg.content"></MarkdownViewer>
        </view>
        <!-- 用户头像 -->
        <view class="message-avatar">
          <image v-if="msg.isUser" class="avatar" src="/static/user.jpg"></image>
        </view>

      </view>
    </scroll-view>
    <view class="input-container">
      <input class="input-message " type="text" v-model="inputMessage" @input="onKeyInput" placeholder="请输入消息"
        @confirm="handleSend" />
      <text class="uni-icon" v-if="showClearIcon" @click="clearIcon">&#xe434;</text>
      <button class="send-button" @click="handleSend">发送</button>
    </view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      chatId: '',
      user_unique_id: 'cqpk1t0nsmmkruf9g7m0',
      timer: null,
      showClearIcon: false,
      firstText: false,
      messages: [],
      inputMessage: '',
      lastMessageId: '',
      currentText: '',
      title: '',
      token: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTcyODgwMDg3NiwiaWF0IjoxNzI4Nzk5OTc2LCJqdGkiOiJjczVtOXE2bTFmMDliNGw0bmU2MCIsInR5cCI6ImFjY2VzcyIsImFwcF9pZCI6ImtpbWkiLCJzdWIiOiJjcXBrMXQwbnNtbWtydWY5ZzdtMCIsInNwYWNlX2lkIjoiY3FwazF0MG5zbW1rcnVmOWc3bGciLCJhYnN0cmFjdF91c2VyX2lkIjoiY3FwazF0MG5zbW1rcnVmOWc3bDAifQ.zKOrCkXFGXWB2LLtBb9UGL-7phOPlgpMUjHuXoSZO9ERhIqCXqQns6ZEtL8o_L8EQkomMU6Jui1O9p0j2-_Q3Q',
      refreshToken: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTczNjU3NTk3NiwiaWF0IjoxNzI4Nzk5OTc2LCJqdGkiOiJjczVtOXE2bTFmMDliNGw0bmU2ZyIsInR5cCI6InJlZnJlc2giLCJhcHBfaWQiOiJraW1pIiwic3ViIjoiY3FwazF0MG5zbW1rcnVmOWc3bTAiLCJzcGFjZV9pZCI6ImNxcGsxdDBuc21ta3J1ZjlnN2xnIiwiYWJzdHJhY3RfdXNlcl9pZCI6ImNxcGsxdDBuc21ta3J1ZjlnN2wwIn0.azWgqL1SX52pqhLRKbOqq--etNzGneRzm9zu8miPuIFULWMvgiW7BQyqoCcu9e0yPeoY8VIE0Oj3LTtdSy6giw'
    };
  },
  unmounted() {
    clearInterval(this.timer)
  }, created() {
    this.timer = setInterval(() => {
      const timeStamp = Date.now()
      const req = [{
        events: [{ event: "_be_active", params: { start_time: timeStamp, end_time: timeStamp, url: "https://kimi.moonshot.cn/chat/cs3sfnalve9uar25glfg", referrer: "", title: "Kimi.ai - 帮你看更大的世界", event_index: 1728696765149 }, local_time_ms: 1728698913706, is_bav: 1, ab_sdk_version: "20183260, 20169060, 20170220, 20151149, 20145781, 20142879, 290769, 298062", session_id: "18d0403e- 0767 - 4980 - a5c8 - df382fb69cf0" }], user: { user_unique_id: this.userUniqueId, web_id: "7400330085250656769" }, header: { app_id: 20001731, os_name: "windows", os_version: "10", device_model: "Windows NT 10.0", language: "zh - CN", platform: "web", sdk_version: "5.1.12_tob", sdk_lib: "js", timezone: 8, tz_offset: -28800, resolution: "2049x1152", browser: "Microsoft Edge", browser_version: "129.0.0.0", referrer: "", referrer_host: "", width: 2049, height: 1152, screen_width: 2049, screen_height: 1152, custom: {} }, local_time: timeStamp, verbose: 1
      }]
      uni.request({
        url: 'https://gator.volces.com/list',
        method: 'POST',
        data: req,
        header: { 'Connection': 'keep-alive', 'Content-type': 'application/json; charset=UTF-8' },
        success: (res) => {
          console.log('keep alive list:', res)
          if (res.statusCode != 200) {
            clearInterval(this.timer)
          }
        },
      })
    }, 60000);
  },
  onHide() {
    const chatid = uni.getStorageSync('chatId')
    console.log("onhide:", chatid)
    if (chatid) {
      this.chatId = chatid
    }

    uni.setStorageSync("messages", this.messages)
    const msgHistory = uni.getStorageSync("messages");

    if (msgHistory) {
      this.messages = msgHistory;
    }

  },
  mounted() {
    const chatid = uni.getStorageSync('chatId')
    console.log("mounted:", chatid)
    const access_token = uni.getStorageSync('access_token');
    if (access_token) {
      this.token = access_token;
    }
    const refresh_token = uni.getStorageSync('refresh_token');
    if (refresh_token) {
      this.refreshToken = refresh_token;
    }
  }, methods: {
    refreshUserToken() {
      uni.request({
        method: 'GET', url: 'https://kimi.moonshot.cn/api/auth/token/refresh',
        header: { "Content-Type": "application/json", Authorization: `Bearer ${this.refreshToken}` },
        success: (res) => {
          console.log('refresh:', this.refreshToken)
          if (res.statusCode == 200) {
            this.token = res.data.access_token;
            this.refreshToken = res.data.refresh_token
            uni.setStorageSync('access_token', this.token);
            uni.setStorageSync('refresh_token', this.refreshToken);
          } else {

            uni.showToast({
              title: "登录过期,请重新登录",
              icon: "none",
            });
            uni.redirectTo({ url: '/pages/login/login' })
          }
        },
        fail: (fail) => {
          uni.showToast({
            title: "登录过期,请重新登录",
            icon: "none",
          });
          uni.redirectTo({ url: '/pages/login/login' })
        },
      });
    },
    keepConnection() {
      const timeStamp = Date.now()

      const req = [{
        events: [{ event: "_be_active", params: { start_time: timeStamp, end_time: timeStamp, url: "https://kimi.moonshot.cn/chat/cs3sfnalve9uar25glfg", referrer: "", title: "Kimi.ai - 帮你看更大的世界", event_index: 1728696765149 }, local_time_ms: 1728698913706, is_bav: 1, ab_sdk_version: "20183260, 20169060, 20170220, 20151149, 20145781, 20142879, 290769, 298062", session_id: "18d0403e- 0767 - 4980 - a5c8 - df382fb69cf0" }], user: { user_unique_id: this.userUniqueId, web_id: "7400330085250656769" }, header: { app_id: 20001731, os_name: "windows", os_version: "10", device_model: "Windows NT 10.0", language: "zh - CN", platform: "web", sdk_version: "5.1.12_tob", sdk_lib: "js", timezone: 8, tz_offset: -28800, resolution: "2049x1152", browser: "Microsoft Edge", browser_version: "129.0.0.0", referrer: "", referrer_host: "", width: 2049, height: 1152, screen_width: 2049, screen_height: 1152, custom: {} }, local_time: timeStamp, verbose: 1
      }]
      uni.request({
        url: 'https://gator.volces.com/list',
        method: 'POST',
        data: req,
        header: { 'Connection': 'keep-alive', 'Content-type': 'application/json; charset=UTF-8' },
        success: (res) => {
          console.log('keep alive list:', res)
          if (res.statusCode != 200) {
            clearInterval(this.timer)
          }
        },
      })
    },
    onKeyInput(event) {

      if (event.target.value.trim) {
        const instance = { "offset": 0, "size": 10, "query": event.target.value }
        console.log(' instance data:', instance)

        uni.request({
          url: 'https://kimi.moonshot.cn/api/prompt-snippet/instance',
          data: instance,
          method: 'POST',
          header: { "Content-Type": "application/json", Authorization: `Bearer ${this.token}` },
          success: (res) => {
            console.log('instance success:', res)
            if (res.statusCode != 200) {
              this.refreshUserToken()
            }

            this.keepConnection()

          },
          fail: (fail) => {
          },
        })

      }
    },
    clearIcon() {
      this.inputMessage = '';
      this.showClearIcon = false;
    },
    clearInput(event) {
      this.inputMessage = event.detail.value;
      if (event.detail.value.length > 0) {
        this.showClearIcon = true;
      } else {
        this.showClearIcon = false;
      }
    },
    handleSend() {
      this.keepConnection()
      if (this.inputMessage.trim()) {
        this.messages.push({ content: this.inputMessage, isUser: true, id: `msg-${this.messages.length}` });

        const data = {
          messages: [{ role: "user", content: this.inputMessage }],
          use_search: false,
          extend: { sidebar: true },
          kimiplus_id: "kimi",
          use_research: false,
          refs: [],
        };
        this.inputMessage = "";
        this.currentText = "";
        this.firstText = true
        const chatid = uni.getStorageSync('chatId')
        const requestTask = uni.request({
          url: `https://kimi.moonshot.cn/api/chat/${chatid}/completion/stream`,
          method: "POST",
          header: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${this.token}`,
          },
          data: data,
          responseType: "text",
          enableChunked: true, // 启用分块接收
          success: (response) => {
            console.log('resp:', response)
            if (response.statusCode == 404) {
              uni.showToast({
                title: "会话过期,请重新登录",
                icon: "none",
              });
              uni.redirectTo({ url: '/pages/login/login' })
            } else if (response.statusCode != 200) {
              this.refreshUserToken()
            }
          },
          fail: (error) => {
            console.error("Failed to send message:", error);
          },
          complete: (com) => {
          }
        });

        requestTask.onHeadersReceived((res) => {
          console.log("header:", res)
        });

        requestTask.onChunkReceived((res) => {
          const uint8Array = new Uint8Array(res.data);
          let text = String.fromCharCode.apply(null, uint8Array);
          text = decodeURIComponent(escape(text))
          // 解析接收到的数据块
          this.processChunk(text);
        });
      }
    },

    processChunk(chunkData) {
      const lines = chunkData.split("\n");

      lines.forEach((line) => {
        if (line.trim()) {
          try {
            const jsonObj = JSON.parse(line.substring(6)); // 移除 "data:" 前缀
            const { text, content, error, event } = jsonObj;

            if (content) {
              this.title = content; // 追加到当前文本
            }

            if (event == "cmpl" && text) {
              this.lastMessageId = text
              this.currentText += text; // 追加到当前文本
              if (this.firstText) {
                this.firstText = false;
                this.messages.push({ content: text, isUser: false, id: `msg-${this.messages.length}` })
                this.lastMessageId = 'msg-' + (this.messages.length - 1)
              } else {

                this.messages[this.messages.length - 1] = { content: this.currentText, isUser: false, id: `msg-${this.messages.length}` }

              }
            } else if (error) {
              const { message } = error;

              this.currentText += message; // 追加到当前文本
            } else if (event == 'all_done') {

              console.log("test", this.currentText)
            } else {
            }

          } catch (error) {
            console.error("Error parsing JSON:", error);
          }
        }
      });
    }

  }
}
</script>


<style scoped>
/* 基础样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #efd8d8;
  padding: 10px;
}

.chat-message {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}

.user-message {
  justify-content: flex-end;
}

.message-bubble {
  background-color: #ebebeb;
  color: #fffbfb;
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
  word-wrap: break-word;
  white-space: normal;
  overflow-x: auto;
}

.user-bubble {
  background-color: #007aff;
  color: #fff;
}

.message-avatar {
  margin-right: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

/* Markdown 样式 */
.markdown-content {
  white-space: pre-wrap;
  /* 保持空格和换行 */
  font-family: monospace;
  /* 等宽字体 */
}

/* 模拟Markdown的标题样式 */
.markdown-content h1 {
  font-size: 24px;
  font-weight: bold;
}

/* 模拟Markdown的链接样式 */
.markdown-content a {
  color: #0000EE;
  text-decoration: underline;
}

/* 模拟Markdown的列表样式 */
.markdown-content ul {
  list-style-type: disc;
  padding-left: 20px;
}

.markdown-content li {
  margin-bottom: 5px;
}

/* 模拟Markdown的引用样式 */
.markdown-content blockquote {
  border-left: 4px solid #ddd;
  padding-left: 10px;
  color: #666;
}

/* 模拟Markdown的代码样式 */
.markdown-content code {
  background-color: #f4f4f4;
  border-radius: 3px;
  padding: 2px 4px;
  font-family: monospace;
}
.input-container {
  display: flex;
  align-items: center; 
  background-color: #f7f7f7;
  border-top: 1px solid #ddd;
  /* 移除了固定高度，以便更灵活地适应内容 */
}

.input-message {
  flex: 1; 
  border-radius: 4px;
  border: 1px solid #ddd;
  margin-right: 10px;
  font-size: 16px; /* 输入框的字体大小 */
  /* 移除了高度设置，使用flex-grow来填充可用空间 */
}

.send-button {
  padding: 0 20px; /* 根据需要调整内边距 */
  background-color: #007aff;
  color: #fff;
  border-radius: 8px;
  border: none;
  font-size: 16px; /* 发送按钮的字体大小 */
  line-height: 40px; /* 设置行高来确保文字垂直居中 */
  height: 40px; /* 设置按钮的高度 */
  cursor: pointer;
  text-align: center; /* 确保文字水平居中 */
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  /* 如果按钮需要适应输入框的高度，可以添加以下两行 */
  flex-shrink: 0; /* 防止按钮在缩小时塌陷 */
}

/* 为了确保placeholder的字体大小与输入时的字体大小一致，可以添加以下样式 */
.input-message::placeholder {
  font-size: 16px; /* placeholder字体大小 */
  color: #aaa; /* placeholder字体颜色 */
}
 
</style>